<?php

/**
 * LaFabbrica.org
 *
 * @author     luigi.pastore (gigi@la-fabbrica.org)
 * @package    LaFabbrica
 * @copyright  Copyright (c) 2011 Luigi Pastore
 * @created  14-apr-2011
 */
class Classes_Core_Layout
{
    /**
     * Singleton instance
     *
     * @var Layout
     */
    protected static $_instance = null;
    
    /**
     * Da Doc Php:
     * __set() is run when writing data to inaccessible properties.
     */
    private $content;
    private $disableLayout;
    
    /**
     * Ritorna istanza di Layout
     *
     * Implementazione del Singleton pattern
     *
     * @return Layout Provides a fluent interface
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    /*
     * Utilizzo questo magic method così posso settare dei placeholder
     * del layout con $layout->var = $value;
     * 
     * La Proprietà $content può contenere un riferimento ad una vista (array('script'=> 'mome view' ))
     * o un testo statico.
     */
    public function __set( $name, $value )
    {
        if( $name == 'content' )
	{
	    if( is_array( $value ) AND !is_null( $value['script'] ) )
		$this->content = $this->parseFile( $value['script'] );
	    else
		$this->content = $value;
	}
	else
	{
	    $this->$name = $value;
	}
	
        return $this;
    }
    
    public function parseFile( $file )
    {
	if( !$this->module OR $this->module == '' )
	    throw new Exceptions( 'Layout non settato' );

	if( !$this->controller OR $this->controller == '' )
	    $this->controller = 'index';

	$view = APPLICATION_PATH . 
	'/modules/' . 
	$this->module . 
	'/views/' . 
	$file . '.phtml';
	
	if( !file_exists( $view ) )
	    throw new Exception( 'File Inesistente'. $view );
	
	ob_start();
	include( $view );
	$content = ob_get_contents();
	ob_end_clean();
	
	return $content;
    }

    public function disableLayout( $value )
    {
	$this->disableLayout = $value ? true : false;
    }


    public function display( $module = 'default' )
    {
	$this->module ? $module : $this->module;

	/**
	 * Layout Principale
	 * Se disableLayout è settata a true esegue diretttamente il parsing
	 * di $content altrimenti esegue il parsing di layout.phtml (che contiene
	 * $this->content)
	 */
	if( $this->disableLayout !== true )
	    $this->output = $this->parseFile( 'layout', $this->module );	
	else
	    $this->output = $this->content;	
	
	return $this->output;
    }
}

